<template>
  <view>
    <view class="navbar">
      <u-icon name="arrow-left" color="#191919" size="20" @click="goBack()" class="back-box"></u-icon>
      <view class="title">修改密码</view>
    </view>
    <view class="phxx-item content">
      <view class="phxx-item-content">
        <view class="bottom">
          <view class="items">
            <text class="til">账号:</text>
            <input class="val" :value="itemList.account" disabled style="right: 26px;" />
          </view>
          <view class="items">
            <view class="til"><span style="color: red">*</span>原始密码:</view>
            <input class="val" v-model="itemList.originalPwd" placeholder="请输入原始密码" maxlength="16"
              :password="showOriginalPwd" />
            <image class="eye-icon" @click="toggleShowOriginalPwd" :src="!showOriginalPwd ? closeEye : openEye" />
          </view>
          <view class="items">
            <view class="til"><span style="color: red">*</span>新密码:</view>
            <input class="val" v-model="itemList.newPwd" placeholder="请输入新密码" maxlength="16" :password="showNewPwd" />
            <image class="eye-icon" @click="toggleShowNewPwd" :src="!showNewPwd ? closeEye : openEye" />
          </view>
          <view class="error" v-if="newpassFlag"><span style="color: red">{{resultNewMess}}</span></view>
          <view class="items">
            <view class="til"><span style="color: red">*</span>确认密码:</view>
            <input class="val" v-model="itemList.againPwd" placeholder="请输入确认密码" maxlength="16"
              :password="showAgainPwd" />
            <image class="eye-icon" @click="toggleShowAgainPwd" :src="!showAgainPwd ? closeEye : openEye" />
          </view>
          <view class="error" v-if="passwordMismatch"><span style="color: red">{{resultMess}}</span></view>
          <view class="btns">
            <button type="primary" @click="handleClick">提 交</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { toast } from '@/utils/common';
  import { userInfos, updateUserPwd } from '@/api/mine/user.js';
  import config from '@/config';
  export default {
    data() {
      return {
        itemList: {
          account: this.$store.state.user.name,
          originalPwd: undefined,
          newPwd: undefined,
          againPwd: undefined
        },
        newpassFlag: false,
        passwordMismatch: false,
        resultNewMess: '请输入8位以上密码（包含英文大小写，数字，特殊符号且不可连续相同）',
        resultMess: '确认密码与新密码不一致，请重新输入',
        showOriginalPwd: true,
        showNewPwd: true,
        showAgainPwd: true
      };
    },
    created() {
      this.getInf()
    },
    onPullDownRefresh() {
      uni.stopPullDownRefresh();
    },
    computed: {
      openEye() {
        return config.baseImgUrl + '/eye.png';
      },
      closeEye() {
        return config.baseImgUrl + '/noeye.png';
      }
    },
    methods: {
      async getInf() {
        let res = await userInfos();
        if (res.code == 200) {
          this.itemList.account = res.data.userName
        }
      },
      goBack() {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          uni.navigateBack({
            delta: 1
          });
        } else {
          // 如果是第一个页面，可以跳转到首页
          uni.switchTab({
            url: '/pages/mine/info/index'
          });
        }
      },
      toggleShowOriginalPwd() {
        this.showOriginalPwd = !this.showOriginalPwd;
      },
      toggleShowNewPwd() {
        this.showNewPwd = !this.showNewPwd;
      },
      toggleShowAgainPwd() {
        this.showAgainPwd = !this.showAgainPwd;
      },
      validatePasswords() {
        const { originalPwd, newPwd, againPwd } = this.itemList;
        this.passwordMismatch = false;
        const validLength = (pwd) => pwd.length >= 8;
        // const validFormat = pwd => /^[a-zA-Z0-9]{6,16}$/.test(pwd);

        if (!originalPwd) {
          toast('请输入原始密码');
          return false;
        }
        if (!newPwd) {
          toast('请输入新密码');
          return false;
        }

        if (!validLength(newPwd)) {
          toast('请输入8位以上新密码');
          return false;
        }
        //校验新密码的规则-
        console.log('密码规则=', /(.)\1/.test(newPwd))
        if (/(.)\1/.test(newPwd)) {
          this.resultNewMess = "新密码需相邻字符不同"
          this.newpassFlag = true;
          return false;
        }

        let passwordRegex = /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,}$/;
        if (!passwordRegex.test(newPwd)) {
          this.resultNewMess = "请输入8位以上密码（包含英文大小写，数字，特殊符号且不可连续相同）"
          this.newpassFlag = true;
          return false;
        }
        this.newpassFlag = false;
        if (!againPwd) {
          toast('请输入确认密码');
          return false;
        }
        if (!validLength(againPwd)) {
          toast('请输入8位以上确认密码');
          return false;
        }
        if (newPwd !== againPwd) {
          this.resultMess = "确认密码与新密码不一致，请重新输入"
          this.passwordMismatch = true;
          return false;
        }


        // 验证通过
        this.passwordMismatch = false;
        return true;
      },
      async handleClick() {
        if (this.validatePasswords()) {
          let data = {
            oldPassword: String(this.itemList.originalPwd),
            newPassword: String(this.itemList.newPwd)
          };
          let res = await updateUserPwd(data);
          if (res.code == 0) {
            toast('修改密码成功');
            setTimeout(() => {
              uni.reLaunch('/pages/mine/index');
            }, 1000);
          } else {
            toast(res.msg);
          }
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .phxx-item {
    width: 700rpx;
    padding: 0 30rpx 30rpx 30rpx;
    box-sizing: border-box;
    margin: 140rpx auto 20rpx auto;
    border-radius: 16rpx;
    background: #fff;
    font-size: 30rpx;
    font-weight: 500;
    color: #333;

    .phxx-item-content {
      .bottom {
        padding: 10rpx 0 0 0;

        >.items {
          padding-bottom: 6rpx;
          display: flex;
          align-items: center;
          border-bottom: 2rpx solid #ccc;
          padding-top: 15px;

          img {
            width: 40rpx;
            height: 40rpx;
          }
        }

        .btns {
          button {
            width: 100%;
            height: 40px !important;
            margin-top: 50px;
            line-height: 40px !important;
          }
        }

        .til {
          width: 25%;
          display: inline-block;
        }

        .val {
          margin-left: 30rpx;
          width: 75%;
          display: inline-block;
          border-radius: 5px;
          height: 30px;
        }
      }
    }
  }
</style>